import 'package:flutter/material.dart';
import 'package:choo_window_manager/choo_window_manager.dart';
import 'package:choo_window_manager/src/window_manager.dart';
import 'package:flutter/services.dart';

part 'app_bar.dart';

/// 窗口拖动控件，用于实现窗口的拖动功能
/// 通过包裹子控件来实现拖动功能
class WindowPanWidget extends StatefulWidget {
  // ignore: library_private_types_in_public_api
  static _WindowPanState? of(BuildContext context) =>
      context.findAncestorStateOfType<_WindowPanState>();

  /// 子控件
  final Widget child;

  final void Function(PointerEnterEvent event)? onEnter;
  final void Function(PointerExitEvent event)? onExit;
  final void Function(PointerHoverEvent event)? onHover;

  /// 是否展开模式
  /// 当为true时，child内的手势将不会影响阻止拖动
  /// 当为false时（默认），child内的手势将影响阻止拖动
  final bool spread;

  /// 构造函数
  /// @param key - 控件key
  /// @param child - 子控件
  const WindowPanWidget({
    super.key,
    required this.child,
    this.onEnter,
    this.onExit,
    this.onHover,
    this.spread = false,
  });

  @override
  State<WindowPanWidget> createState() => _WindowPanState();
}

/// 窗口拖动控件的状态管理类
class _WindowPanState extends State<WindowPanWidget> with WindowManagerEvent {
  bool? _spread;

  bool get spread {
    if (_spread == null) {
      return widget.spread;
    }
    return _spread!;
  }

  set spread(bool? spread) {
    setState(() {
      _spread = spread;
    });
  }

  @override
  initState() {
    super.initState();
    spread = widget.spread;
  }

  /// 清理窗口拖动相关的监听器
  /// 移除预拖动监听器(removePrePanListener)和拖动监听器(removePanListener)
  @override
  void dispose() {
    super.dispose();
    WindowManagerEvent.removePrePanListener(this);
    WindowManagerEvent.removePanListener(this);
  }

  @override
  Widget build(BuildContext context) {
    Widget child = widget.child;

    if (!spread) {
      child = GestureDetector(
        // 处理拖动手势事件，将阻止拖动行为
        onPanStart: (details) {},
        onPanEnd: (details) {},
        onPanCancel: () {},
        child: child,
      );
    }

    // 构建窗口拖动控件
    // 使用GestureDetector处理拖动手势
    return GestureDetector(
      // 开始拖动时添加监听器
      onPanStart: (details) {
        WindowManagerEvent.addPanListener(this);
      },
      // 结束拖动时移除监听器
      onPanEnd: (details) {
        WindowManagerEvent.removePanListener(this);
      },
      // 取消拖动时移除监听器
      onPanCancel: () {
        WindowManagerEvent.removePanListener(this);
      },
      child: MouseRegion(
        // 鼠标进入区域时添加预拖动监听器
        onEnter: (event) {
          widget.onEnter?.call(event);
          WindowManagerEvent.addPrePanListener(this);
        },
        // 鼠标离开区域时移除预拖动监听器
        onExit: (event) {
          widget.onExit?.call(event);
          WindowManagerEvent.removePrePanListener(this);
        },
        child: child,
      ),
    );
  }
}
